<?php

/**
 * UCModMessageMgr is a mannager to send/get request/notice/letter
 * @contact: wuzhijian@snda.com
 */

define("MD_ROOT_PATH",    dirname(__FILE__) . "/../../../");
define("MD_UNIFIED_PATH", MD_ROOT_PATH . "unified/");
define("MD_MSG_PATH",     MD_ROOT_PATH . "uc/models/message/");


define('MSG_MAX_PARTICIPANTS', 20);         //群发邮件最大参与人数
define('MSG_MAX_REPLY'       , 1000);       //信件回复数上限
define('MSG_SHOWN_REPLY'     , 100);        //展示回复数上限
define('CANDY_MM_ID'         , 1235625354); //糖果妹SDID
#define('CANDY_MM_ID'         , 1108391525); //糖果妹SDID //debug


class UCModMessageMgr
{
	private $_sdid;
	private $_last_error;


	function __construct($sdid) {
		require_once(MD_UNIFIED_PATH . "SDOApiSystemMessageService.php");
		require_once(MD_UNIFIED_PATH . "SDOApiTopicService.php");
		require_once(MD_UNIFIED_PATH . "SDOApiTopicMemberService.php");
		require_once(MD_UNIFIED_PATH . "SDOApiMessageTextService.php");
		require_once(MD_UNIFIED_PATH . "SDOApiCommonMessageService.php");
		require_once(MD_ROOT_PATH    . "uc/models/relation/UCModRelation.php");
		require_once(MD_ROOT_PATH    . "uc/libraries/UCLibMISApi.php");

		$this->_sdid       = $sdid;
		$this->_last_error = '';
	}

	public function getErrorInfo() {
		return $this->_last_error;
	}

	/**
	 * @purpose: set error info
	 */
	private function _setE($err_log, $func) {
		$this->_last_error = sprintf("Error in the function[%s]: %s\n", $func, $err_log);
		return true;
	}

	private function _isApiFail(&$result) {
		return SDOSocket::isError($result) || $result["code"] != 0;
	}

	/**
	 * @purpose: 内容预审核
	 */
	private function _MisCheck($content) {
		$ret = UCLibMISApi::check($this->_sdid, UC_MIS_CHANNEL_MESSAGE, $content);
		return $ret;
	}

	/**
	 * @purpose: 内容审核。入审核库
	 * @return true or false on failure
	 */
	private function _MisAdd2Q($type, $rec_id, $content, $reply_id=null, $reply_owner_id=null) {
		return false;//产品需求变更：“消息”不入MIS

		switch($type) {
			case "letter" : $type_id = 'L'; break;
			case "reply"  : $type_id = 'R'; break;
			case "request": $type_id = 'Q'; break;
			case "notice" : $type_id = 'N'; break;
			default: exit("FATAL ERROR in ".__METHOD__ . ", the param \$type must be correct!\n");
		}
		if ($type == 'reply') {
			$db_rec_id = sprintf("%s:%s,%d,%d", $type_id, $rec_id, intval($reply_id), intval($reply_owner_id));
		} else {
			$db_rec_id = sprintf("%s:%s", $type_id, $rec_id);
		}
		$reason = UCLibMISApi::getReason();

		$ret = UCLibMISApi::add2Q($this->_sdid, UC_MIS_CHANNEL_MESSAGE, $content, $db_rec_id, $reason);
		return $ret === false ? false : true;
	}


	public function checkInbox() {
		$result = SDOApiCommonMessageService::getMessageAmount($this->_sdid);
		if ($this->_isApiFail($result)) {
			$this->_setE("checkInbox() call api failed", __METHOD__);
			return false;
		}
		$result = SDOApiHelper::getOneResult($result);

		$msg_total = $result['msgTotalCount'];
		$msg_total < $result['msgUnreadCount'] && $msg_total = $result['msgUnreadCount'];

		$req_total = $result['reqTotalCount'];
		$req_total < $result['reqUnreadCount'] && $req_total = $result['reqUnreadCount'];

		$not_total = $result['notiTotalCount'];
		$not_total < $result['notUnreadCount'] && $not_total = $result['notUnreadCount'];

		return array(
			"letter_unread"  => $result['msgUnreadCount'],
			"letter_all"     => $msg_total,
			"request_unread" => $result['reqUnreadCount'],
			"request_all"    => $req_total,
			"notice_unread"  => $result['notUnreadCount'],
			"notice_all"     => $not_total,
			"total_unread"   => $result['msgUnreadCount']+$result['reqUnreadCount']+$result['notUnreadCount'],
			"lastmsgtime"    => intval($result['lastmsgtime']/1000),     //最后一次收到消息的时间戳
			);
	}

	/**
	 * @purpose: 设置“已读”状态
	 * @param msg_id: 消息id
	 *        type  : 消息类型{letter,request,notice,alltype}
	 *        all   : 是否设置当前类别下的所有消息为已读。当为true时，程序将忽略参数msg_id
	 */
	public function setAlreadyRead($type, $msg_id, $all=false) {
		if ($type == 'notice') {
			if (true === $all) {
				$result = SDOApiSystemMessageService::updateAllSystemNotify($this->_sdid);
			} else {
				$result = SDOApiSystemMessageService::updateSystemNotify($msg_id, $this->_sdid);
			}


		} else if ($type == 'request') {
			if (true === $all) {
				$result = SDOApiSystemMessageService::updateAllPersonalRequest($this->_sdid);
			} else {
				$result = SDOApiSystemMessageService::updatePersonalRequest($msg_id, $this->_sdid);
			}


		} else if ($type == 'letter')  {
			if (true === $all) {
				$result = SDOApiTopicService::updateAllUnReadTopic($this->_sdid);
			} else {
				$result = SDOApiTopicService::updateTopic($this->_sdid, $msg_id);
			}


		} else if ($type == 'alltype') {
			SDOApiSystemMessageService::updateAllSystemNotify($this->_sdid);
			SDOApiSystemMessageService::updateAllPersonalRequest($this->_sdid);
			SDOApiTopicService::updateAllUnReadTopic($this->_sdid);

			return true;


		} else {
			$this->_setE('param $type err', __METHOD__);
			return false;


		}


		if ($this->_isApiFail($result)) {
			$this->_setE('setAlreadyRead() call api failed', __METHOD__);
			return false;
		}
		return true;
	}

	/**
	 * 删除所有已读消息
	 */
	public function deleteAllAlreadyReadMsg($type) {

		if ($type == 'notice') {
			$result = SDOApiSystemMessageService::deleteAllReadedSystemNotify($this->_sdid);
		} else {
			$this->_setE('$type err', __METHOD__);
			return false;
		}

		if ($this->_isApiFail($result)) {
			$this->_setE('call api failed', __METHOD__);
			return false;
		}

		return true;
	}

	/**
	 * 发送系统消息
	 * @param str_type: 类型
	 * @param receiver: 接收者ID
	 * @param data    : 消息数据
	 * @return true or false on failure
	 */
	public function sendNotice($str_type, $receiver_id, $data=null) {
		#所有的通知类型
		$all_types = array(1 =>"new_comment",			#新增评论
						   2 =>"rm_twitter",			#推它被系统删除
						   3 =>"new_leave_msg",			#新增留言
						   4 =>"new_leavemsg_reply",	#新增回复
						   5 =>"birthday",				#生日提醒
						   #6 =>"system_active_user",	# (供系统后台调用)系统已将你在游戏中的好友自动加为糖果社区好友
						   #7 =>"system_import_user",	# (供系统后台调用)X是你游戏中的好友，系统已经把Ta自动加为你的好友啦
						   8 =>"add_fri_feedback",		#请求加好友成功后，给发出邀请者的一个回馈通知
						   9 =>"someone_added_u",		#A加B为好友后，B将收到一个通知
						   10=>"copy_twitter",			#转载推他
						   11=>"at_twitter",			#@twitter
						   12=>"graph_plaintext",
						   13=>"graph_html",
						   14=>"at_twitter_v2",			#@twitter version2
						   15=>"rm_from_whitelist",		#踢出棒棒堂白名单时的通知
						);
		$type = array_search($str_type, $all_types);
		if (false === $type) {
			$this->_setE("str_type set error", __METHOD__);
			return false;
		}

		require_once(MD_MSG_PATH . "notice/type{$type}.php");
		$content = call_user_func_array("msg_notice_type{$type}_encoder", $data);

		$result = SDOApiSystemMessageService::addSystemNotify(0, $receiver_id, $content, $type);
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiSystemMessageService::addSystemNotify return failure", __METHOD__);
			return false;
		}

		return true;
	}

	/**
	 * @purpose: 获取notice列表
	 */
	public function getNoticeList($start, $count, &$total_results) {
		if ($this->_sdid <= 0) {
			$this->_setE("pls set sdid when create the obj. i.e: \$o=new UCModMessageMgr(sdid)", __METHOD__);
			return false;
		}
		$start = abs(intval($start));
		$count = abs(intval($count));

		$result = SDOApiSystemMessageService::getSystemNotify($this->_sdid, array("startIndex"=>$start, "count"=>$count));
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiSystemMessageService::getSystemNotify return failure", __METHOD__);
			return false;
		}
		$total_results = $result["data"]["totalResults"];
		return SDOApiHelper::getArrayResult($result);
	}

	/**
	 * @purpose: 获取单条notice
	 */
	public function getOneNotice($id) {
		if ($this->_sdid <= 0) {
			$this->_setE("pls set sdid when create the obj. i.e: \$o=new UCModMessageMgr(sdid)", __METHOD__);
			return false;
		}

		$id = intval($id);

		$result = SDOApiSystemMessageService::getASystemNotify($id, $this->_sdid);
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiSystemMessageService::getASystemNotify return failure", __METHOD__);
			return false;
		}
		$one_notice = SDOApiHelper::getOneResult($result, 'err');
		if ($one_notice == 'err') return false;
		return $one_notice;
	}


	/**
	 * 发送请求
	 * @param str_type: 类型
	 * @param receiver, int or array: 接收者ID
	 * @param data    : 消息数据
	 * @return true or false or array
	 */
	public function sendRequest($str_type, $receiver_id, $data=null) {
		#批量发请求最多为10
		$n_max_batch = 10;
		#所有的请求类型
		$all_types = array(
						   1=>"play_game",			#玩游戏
						   2=>"add_friend",			#加好友
						   3=>"add_friend_notify",	#通知加好友
						   4=>"app_common",			#提供给app的通用类型
						  );
		$type = array_search($str_type, $all_types);
		if (false === $type) {
			$this->_setE("str_type set error", __METHOD__);
			return false;
		}

		require_once(MD_MSG_PATH . "request/type{$type}.php");
		$content = call_user_func_array("msg_request_type{$type}_encoder", $data);

		!is_array($receiver_id) && $receiver_id = array($receiver_id);
		$receiver_id = array_slice($receiver_id, 0, $n_max_batch);

		$ret = array();

		foreach($receiver_id as $r_id) {
			$result = SDOApiSystemMessageService::addPersonalRequest($this->_sdid, $r_id, $content, $type);
			if ($this->_isApiFail($result)) {
				$this->_setE("SDOApiSystemMessageService::addPersonalRequest return failure,r_id=$rid", __METHOD__);
				$ret[] = false;
			}
			$ret[] = true;
		}

		return count($ret) == 1 ? $ret[0] : $ret;
	}

	/**
	 * @purpose: 获取request列表
	 */
	public function getRequestList($start, $count, &$total_results) {
		if ($this->_sdid <= 0) {
			$this->_setE("pls set sdid when create the obj. i.e: \$o=new UCModMessageMgr(sdid)", __METHOD__);
			return false;
		}
		$start = abs(intval($start));
		$count = abs(intval($count));

		$result = SDOApiSystemMessageService::getPersonalRequest($this->_sdid, array("startIndex"=>$start, "count"=>$count));
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiSystemMessageService::getPersonalRequest return failure", __METHOD__);
			return false;
		}

		$total_results = $result["data"]['totalResults'];
		return SDOApiHelper::getArrayResult($result);
	}

	/**
	 * @purpose: 获取单条request
	 */
	public function getOneRequest($id) {
		if ($this->_sdid <= 0) {
			$this->_setE("pls set sdid when create the obj. i.e: \$o=new UCModMessageMgr(sdid)", __METHOD__);
			return false;
		}

		$id = intval($id);

		$result = SDOApiSystemMessageService::getAPersonalRequest($id, $this->_sdid);
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiSystemMessageService::getAPersonalRequest return failure", __METHOD__);
			return false;
		}
		$one_request = SDOApiHelper::getOneResult($result, 'err');
		if ($one_request == 'err') return false;
		return $one_request;
	}

	public function deleteMsgAll($msg_type) {
		switch($msg_type) {
			case 'request':
				$result = SDOApiSystemMessageService::deleteAllPersonalRequest($this->_sdid);
				break;
			default:
				$this->_setE('param $msg_type err', __METHOD__);
				return false;
		}

		if ($this->_isApiFail($result)) {
			$this->_setE("call Api failed", __METHOD__);
			return false;
		}
		return true;
	}
	public function deleteMessage($msg_type, $msg_id, $reply_id=null) {

		if ("notice" == $msg_type) {
			$result = SDOApiSystemMessageService::deleteSystemNotify($this->_sdid, (int)$msg_id);
		} else if ("request" == $msg_type) {
			$result = SDOApiSystemMessageService::deletePersonalRequest($this->_sdid, (int)$msg_id);
		} else if ("letter" == $msg_type) {
			$result = SDOApiTopicService::deleteTopic($this->_sdid, $msg_id);
		} else if ("reply" == $msg_type) {
			$result = SDOApiMessageTextService::deleteMessageText($reply_id, $this->_sdid, $msg_id);
		} else {
			$this->_setE('param $msg_type err', __METHOD__);
			return false;
		}

		if ($this->_isApiFail($result)) {
			$this->_setE("call Api failed", __METHOD__);
			return false;
		}
		return true;
	}

	/**
	 * @return true or RELATION errno
	 */
	public function addFriendReq($msg_id) {
		//      step1 读取该条req，得到senderid & receiverid
		//      step2 将两sdid为好友
		//      step3.0 若添加好友成功，则deleteRequest
		$msg_id = intval($msg_id);

		$msg = $this->getOneRequest($msg_id);
		if (false === $msg) {
			return false;
		}
		$senderid   = (int)$msg['senderid'];
		$receiverid = (int)$msg['receiverid'];

		if ($senderid <= 0 || $receiverid <= 0) {
			$this->_setE("senderid or receiverid is empty", __METHOD__);
			return false;
		}

		if ($receiverid != $this->_sdid) {
			$this->_setE("receiver is not current user", __METHOD__);
			return false;
		}

		$relation = new UCModRelation($receiverid);
		if ($relation->addRelation($senderid)) {
			$this->deleteMessage('request', $msg_id);
			return true;
		} else {
			$errno = $relation->getLastErrno();

			if (in_array($errno, array(UCConfRelation::ADD_RELATION_ERROR_IS_SELF,UCConfRelation::ADD_RELATION_ERROR_FOLLOWED))) {
				$this->deleteMessage('request', $msg_id);
			}

			return $errno;
		}


	}

	/**
	 * @purpose: 发送新Letter
	 * @param participants: string("id1,id2,...,idn") 与会人员列表
	 * @param content text: 信件内容
	 * @return: topic_id or false on failure
	 */
	public function sendNewLetter($participants, $content, &$alert_msg) {
		$preg_ret = preg_match("/^(\d{1,15},){1,".(MSG_MAX_PARTICIPANTS-1)."}\d{1,15}$/", $participants);
		if (false === $preg_ret || $preg_ret <= 0) {
			$this->_setE("participants 参数格式错误", __METHOD__);
			$alert_msg = "参数错误";
			return false;
		}

		//发新topic时，将自己从userList中排除
		$participants = trim(str_replace(",{$this->_sdid},", ",", ",{$participants},"), ",");


		$len = strlen($content);
		if ($len <= 0 && $content > 10240) {
			$this->_setE("content参数长度过大或过小", __METHOD__);
			$alert_msg = "发表文字长度不符合要求";
			return false;
		}

		//MIS校验
		$mis_ret = $this->_MisCheck($content);

		if (UC_MIS_RESULT_BAD == $mis_ret) {                  //强敏感词
			$this->_setE("MIS check: bad result", __METHOD__);
			$alert_msg = "请勿发表带敏感词的内容";
			return false;

		} else if (UC_MIS_RESULT_FREQ_LIMIT == $mis_ret) {    //频率过快
			$this->_setE("MIS check: freq limit", __METHOD__);
			$alert_msg = "发表频率过快";
			return false;

		} else {  //UC_MIS_RESULT_PASS、UC_MIS_RESULT_QUEUE、false

			$result = SDOApiTopicService::addTopic($this->_sdid, $participants, $content);
			if ($this->_isApiFail($result)) {
				$this->_setE("call API addTopic failed", __METHOD__);
				$alert_msg = "系统繁忙，请稍后再试";
				return false;                                 //统一XXAPI错误
			}
			$topic_id = $result['data']['data'];

			UCLibStat::statex(UCConfStat::STAT_MSG_USER, $this->_sdid); //发送私信用户数
			UCLibStat::action(UCConfStat::STAT_MSG);                    //发送私信条数

			if (UC_MIS_RESULT_QUEUE == $mis_ret) {
				$this->_MisAdd2Q('letter', $topic_id, $content);
			}

			return $topic_id;                                 //-----成功
		}
	}

	/**
	 * @purpose: 对已存在的主题添加内容
	 */
	public function sendLetter($topic_id, $content, &$alert_msg) {
		$len = strlen($content);
		if ($len <= 0 && $content >= 10240) {
			$this->_setE("content参数长度过大或过小", __METHOD__);
			$alert_msg = "发表的内容长度不符合要求";
			return false;
		}


		//MIS校验
		$mis_ret = $this->_MisCheck($content);

		if (UC_MIS_RESULT_BAD == $mis_ret) {                  //强敏感词
			$this->_setE("MIS check: bad result", __METHOD__);
			$alert_msg = "请勿发表带敏感词的内容";
			return false;

		} else if (UC_MIS_RESULT_FREQ_LIMIT == $mis_ret) {    //频率过快
			$this->_setE("MIS check: freq limit", __METHOD__);
			$alert_msg = "发表频率过快";
			return false;

		} else {  //UC_MIS_RESULT_PASS、UC_MIS_RESULT_QUEUE、false

			$result = SDOApiMessageTextService::addMessageText($this->_sdid, $topic_id, $content);
			if ($this->_isApiFail($result)) {
				$this->_setE("call API addMessageText failed", __METHOD__);
				$alert_msg = "系统繁忙，请稍后再试";
				return false;                                 //统一XXAPI错误
			}
			$reply_id = $result['data']['data'];

			UCLibStat::statex(UCConfStat::STAT_MSG_USER, $this->_sdid); //发送私信用户数
			UCLibStat::action(UCConfStat::STAT_MSG);                    //发送私信条数

			if (UC_MIS_RESULT_QUEUE == $mis_ret) {
				$this->_MisAdd2Q('reply', $topic_id, $content, $reply_id, $this->_sdid);
			}

			return $reply_id;                                 //-----成功
		}
	}

	/**
	 * @purpose: 获取回信列表
	 */
	public function getMsgtextList($topic_id, $cur_total_num, $count=null, &$total_results=null) {
		$count === null && $count = MSG_MAX_REPLY - $cur_total_num;

		$result = SDOApiMessageTextService::getMessageText($topic_id, array(
					"startIndex"=>$cur_total_num,
					"count"     =>$count,
					));

		if ($this->_isApiFail($result)) {
			$this->_setE("call Api failed", __METHOD__);
			return false;
		}

		$total_results = $result["data"]["totalResults"];

		//set newflag to 2
		$this->setAlreadyRead('letter', $topic_id);

		return SDOApiHelper::getArrayResult($result);
	}

	/**
	 * @purpose: 获取LetterTitle列表
	 */
	public function getLetterTitleList($start, $count, &$total_results) {
		if ($this->_sdid <= 0) {
			$this->_setE("pls set sdid when create the obj. i.e: \$o=new UCModMessageMgr(sdid)", __METHOD__);
			return false;
		}
		$start = abs(intval($start));
		$count = abs(intval($count));

		$result = SDOApiTopicService::getTopic($this->_sdid, array("startIndex"=>$start, "count"=>$count));
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiTopicService::getTopic return failure", __METHOD__);
			return false;
		}
		$total_results = $result["data"]["totalResults"];
		return SDOApiHelper::getArrayResult($result);
	}

	/**
	 * @purpose: 获取一个topic的全部member
	 * @return array or false on failure
	 */
	public function getTopicMembers($letter_id) {
		if ($this->_sdid <= 0) {
			$this->_setE("pls set sdid when create the obj. i.e: \$o=new UCModMessageMgr(sdid)", __METHOD__);
			return false;
		}

		$result = SDOApiTopicMemberService::getTopicMember($letter_id, array("startIndex"=>0, "count"=>MSG_MAX_PARTICIPANTS+10)); //比规定的多取一点
		if ($this->_isApiFail($result)) {
			$this->_setE("SDOApiTopicMemberService::getTopicMember return failure", __METHOD__);
			return false;
		}
		$total_results = $result["data"]["totalResults"];
		$result = SDOApiHelper::getArrayResult($result);

		$members = array();
		foreach($result as $rt) {
			$members[] = $rt['sdid'];
		}

		return $members;
	}

	/**
	 * @purpose: 根据当前条件返回更新信息
	 * @param letter_id: 当前letter的topic_id
	 * @param participants: 参与人列表，格式如: 123,456,789
	 * @param cur_total_num: 当前回复数
	 * @return array() or false on failure
	 */
	public function getLetterNewInfo($letter_id, $participants, $cur_total_num) {
		$ret = array();

		//回信的情况
		$msgtext_list = $this->getMsgtextList($letter_id, $cur_total_num);
		if (false === $msgtext_list) {
			return false;
		} else {
			$owner_ids = array();
			$owner_info= array();
			foreach($msgtext_list as &$msg) {
				$owner_ids[] = $msg['ownerid'];
			}
			$owner_ids  = array_unique($owner_ids);
			$owner_info = UCModUserInfo::getUserInfos($owner_ids, array(USERINFO_NICKNAME,USERINFO_AVATAR_30));

			foreach($msgtext_list as &$msg) {
				$owner_id = $msg['ownerid'];
				$msg['nick']   = $owner_info[$owner_id][USERINFO_NICKNAME];
				$msg['avatar'] = $owner_info[$owner_id][USERINFO_AVATAR_30];
				$msg['time']   = self::fmtTime($msg['createTime'], 2);
				//content ------ 前端json中用到该字段
				//ownerid ------ 前端json中用到该字段
			}

			$ret['msgtext'] = &$msgtext_list;
		}

		//与会者的情况
		$server_member = $this->getTopicMembers($letter_id); //服务端的与会者名单
		$client_member = explode(',', $participants);        //客户端的与会者名单

		if (false === $server_member) {
			return false;
		} else {
			$ret['papt_add'] = array_diff($server_member, $client_member); //需增加的与会者名单
			$ret['papt_del'] = array_diff($client_member, $server_member); //需删除的与会者名单

			sort($ret['papt_add']); //从0开始重计索引
			sort($ret['papt_del']); //从0开始重计索引
		}

		return $ret;
	}

	/**
	 * @purpose: 使用户成为信件成员
	 * @param users, string or array: 用户名单
	 * @param letter_id, 信件id
	 * @return true or false on failure
	 */
	public function addUsersToLetter($users, $letter_id, &$fail_users=array()) {
		!is_array($users) && $users = array(0=>$users);
		$fail_users = array();

		$mbm = $this->getTopicMembers($letter_id);
		if (false === $mbm) return false;

		$add_num = count($users);
		$old_num = count($mbm);

		if ($old_num + $add_num > MSG_MAX_PARTICIPANTS) {
			return false;
		}

		if ($old_num + $add_num == MSG_MAX_PARTICIPANTS) {
			UCLibStat::action(UCConfStat::STAT_MSG_LIMIT); //达到邮件组上限的数量
		}


		foreach($users as $u) {
			$result = SDOApiTopicService::addUserToTopic($u, $letter_id);
			if ($this->_isApiFail($result)) {
				return false;//有一个没加入，则为失败。
			}
		}

		return true;
	}

	/**
	 * @purpose: 判断当前人是否为指定会话的当前参与者
	 * @memo: 若指定topic_members，则从该数组中查;若不指定，则根据letter_id从统一XX中查找
	 */
	public function isTopicMember($letter_id, $topic_members=null) {
		if (!is_array($topic_members)) {
			$topic_members = $this->getTopicMembers($letter_id);
			is_array($topic_members) || $topic_members = array();
		}

		return in_array($this->_sdid, $topic_members) ? true : false;
	}

	/**
	 * @purpose: 从MIS接收record_id，删除数据
	 */
	static public function misDel($mis_rec_id) {
		return true; //产品需求更改后，已无misDel的必要，故暂移除以下代码

		$tmp = explode(":", $mis_rec_id);
		$msg_type = $tmp[0];
		$msg_id   = $tmp[1];

		if ($msg_type == 'L') {         //del topic
			$result = SDOApiTopicService::deleteCommonTopictopicId($msg_id);

		} else if ($msg_type == 'R') {  //del reply
			$tmp2 = explode(',', $tmp[1]);
			$owner_id = $tmp2[2];
			$reply_id = $tmp2[1];
			$topic_id = $tmp2[0];

			$result = SDOApiMessageTextService::deleteMessageText($reply_id, $owner_id, $topic_id);

		} else {
			return false;
		}

		if (SDOSocket::isError($result) || $result["code"] != 0) { return false; }

		return true;
	}

	/**
	 * @purpose: “消息”模块专用时间函数
	 */
	static public function fmtTime($time, $style=1) {
		$time  = intval($time/1000);//毫秒转秒
		$today = strtotime("today");//date("Y-m-d 00:00:00");

		switch($style) {
			case 1:
				if ($time >= $today) return date("G:i"   , $time);
				else                 return date("n月j日", $time);
				break;
			case 2:
				if ($time >= $today) return date("G:i:s"       , $time);
				else                 return date("n月j日 G:i:s", $time);
				break;
			default:
				return date("n月j日 G:i:s", $time);
		}
	}

	static public function makeToken($cate, $plain_text) {
		switch($cate) {
			case 'add_fri':
				$key   = "man*@de>l/w+oo";
				$token = substr(md5($key.$plain_text), 7, 6);
				break;
			case 'set_all_read':
				$key   = "ca3Xn<3784d_ym";
				$token = substr(md5($key.$plain_text), 12, 16);
				break;
			case 'delete_all':
				$key   = "lUx39A+-3;#dlm";
				$token = substr(md5($key.$plain_text), 3, 16);
				break;
			case 'del_already_read':
				$key   = "wxxuZwdHI*9Jian";
				$token = substr(md5($key.$plain_text), 8, 16);
				break;
			default:
				$token = '';
				;
		}
		return $token;
	}
}

